package manager.auth.service.impl;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import manager.auth.dao.SysUserDao;
import manager.auth.service.UserAuthService;
import manager.auth.vo.SysUserVO;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.stereotype.Service;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.List;
@Service(value = "userAuthService")
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private SysUserDao sysUserDao;
    public String authentication(String username, String password) {
        String token="";
        try {
            SysUserVO sysUserVO =new SysUserVO();
            sysUserVO.setUsername(username);
            List<SysUserVO> userList = sysUserDao.select(sysUserVO);
            if(userList.size()==0){
                return null;
            }
            String adminPassword = BCrypt.hashpw(password, userList.get(0).getSalt());
            if(!adminPassword.equals(userList.get(0).getPassword())){
                return null;
            }
            //校验通过后生成token
            ClassPathResource classPathResource = new ClassPathResource("huaweishop.jks");
            KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "huaweishop".toCharArray());
            KeyPair keyPair = keyStoreKeyFactory.getKeyPair("huaweishop");
            RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
            token= Jwts.builder().claim("userId", userList.get(0).getId())
                    .claim("username", username)
                    .claim("password",adminPassword)
                    .setExpiration(DateTime.now().plusMinutes(30).toDate())
                    .signWith(SignatureAlgorithm.RS256, privateKey)
                    .compact();
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }
}
